<?php
/**
 * Author: Administrator
 * Date: 2022/7/17 1:08
 */

namespace DesignPatterns\Structural\FluentInterface;


class SQL
{

    protected $table;
    protected $fields = array();
    protected $where = array();
    protected $orderBy = array();

    public function __construct($table)
    {
        $this->table = $table;
    }


    public function select($fields)
    {
        $this->fields = $fields;
        return $this;
    }

    public function where($condition)
    {
        $this->where[] = $condition;
        return $this;
    }

    public function orderBy($field, $sort)
    {
        $this->orderBy[$field] = $sort;
        return $this;
    }

    public function getQuery()
    {
        return "SELECT " . implode(',', array_map(function ($f) {
                return "`$f`";
            }, array_filter($this->fields)))
            . " FROM $this->table WHERE " . implode(' AND ', $this->where)
            . " ORDER BY " . implode(',', array_map(function ($k, $v) {
                $v = $v == 'DESC' ? 'DESC' : 'ASC';
                return " $k $v ";
            }, array_keys($this->orderBy), array_values($this->orderBy)));
    }

}